'''
This function output the fasta sequence if the 
sequence from the input *.fa ( arg[1] )file contains 
any short fragment in the fragments file ( arg[2] ).
'''
import os
import getopt
import sys
import string
from parse_fasta_file import get_tag_seq_from_fasta_w_substr
from parse_fasta_file import print_fasta
def usage():
    sys.stderr.write( "Working dir is " + os.getcwd() + '\n' )
    print "usage: ", sys.argv[0]
    print "The three parameters should be "
    print "(1) fasta file name"
    print "(2) short fragments file name"
    print "(3) output file name"
    sys.exit( 2 )

def getSeqWithShortFragment( faFileN, fragFileN, ofileN ):
    faFile = open( faFileN, "r" )
    fragFile = open( fragFileN, "r" )
    if os.path.exists( ofileN ):
        os.remove( ofileN )
    fragments = fragFile.readlines()
    while True:
        [tag, seq] = get_tag_seq_from_fasta_w_substr( faFile, '>' )
        if seq == "":
            break
        for fragment in fragments:
            fragment = fragment.strip()
            occurence = seq.find( fragment )
            if occurence >= 0:
                print tag, fragment, occurence
                print_fasta( ofileN, tag, seq )
                break
    faFile.close()
    fragFile.close()

def main():
    try:
        opts, args = getopt.getopt( sys.argv[1:], 'h', ["help"] )
    except getopt.error:
        usage()
        sys.exit( 2 );
    # process options and argument 
    for o in opts:
        if o in ( "-h", "--help" ):
            usage()
            sys.exit();
    if len( args ) == 3 :
        faFileN = args[0]
        fragFileN = args[1]
        ofileN = args[2]
        getSeqWithShortFragment( faFileN, fragFileN, ofileN );
    else:
        print  string.join( args, ' ' )
        print  str( len( args ) ) + " args are provided."
        usage()

if __name__ == '__main__':
    main()

